<template>
  <div class="history-sql-container">
    <el-card class="box-card">
      <template #header>
        <div class="list-header">
          <h2>历史SQL查询</h2>
          <div class="header-actions">
            <el-tooltip content="关闭" placement="bottom">
              <el-button
                  type="info"
                  @click="$emit('closeHistorySql')"
                  size="small"
                  class="icon-btn"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="地址名称">
          <el-select
            v-model="searchForm.addressName"
            placeholder="请选择地址"
            filterable
            clearable
            @change="handleAddressChange"
            style="width: 200px"
          >
            <el-option
              v-for="addr in addressList"
              :key="addr.id"
              :label="addr.name"
              :value="addr.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库名">
          <el-select
            v-model="searchForm.dbName"
            placeholder="请选择库名"
            filterable
            clearable
            @change="handleDbChange"
            style="width: 180px"
          >
            <el-option
              v-for="db in dbOptions"
              :key="db"
              :label="db"
              :value="db"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表名">
          <el-select
            v-model="searchForm.tableName"
            placeholder="请选择表名"
            filterable
            clearable
            :disabled="!searchForm.dbName"
            style="width: 180px"
          >
            <el-option
              v-for="table in tableOptions"
              :key="table"
              :label="table"
              :value="table"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px"

          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px"

          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="tableLoading" :disabled="tableLoading" :icon="Search">搜索</el-button>
          <el-button @click="resetForm" :disabled="tableLoading" :icon="RefreshRight">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          :data="sqlList"
          border
          style="width: 100%"
          v-loading="tableLoading"
          element-loading-text="加载中..."
          :empty-text="emptyText"
          stripe
          highlight-current-row
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="addressName" label="地址名称" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column prop="dbName" label="库名" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="tableName" label="表名" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="sqlStatement" label="SQL语句" min-width="300" show-overflow-tooltip />
          <el-table-column prop="executeTime" label="执行时间" min-width="180" align="center" />
          <el-table-column prop="status" label="状态" min-width="100" align="center" fixed="right">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'SUCCESS' ? 'success' : 'danger'">
                {{ scope.row.status === 'SUCCESS' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :disabled="tableLoading"
            :hide-on-single-page="pagination.total <= pagination.pageSize"
            class="responsive-pagination"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Close, Search, RefreshRight } from '@element-plus/icons-vue'
import api from '@/api'
import { ElMessage } from 'element-plus'


// 搜索表单数据
const searchForm = reactive({
  addressName: '',
  id:'',
  host: '',
  port: '',
  userName: '',
  passWord: '',
  dbName: '',
  tableName: '',
  startTime: '',
  endTime: ''
})

// 表格数据
const sqlList = ref([])
const addressList = ref([])
const dbOptions = ref([])
const tableOptions = ref([])
const selectedAddress = ref(null)
const tableLoading = ref(false)
const emptyText = ref('暂无数据')


// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const data = {
      deleted: 0
    }
    const response = await api.binlog.list(data, 1, 1000)
    if (response.code === 200) {
      addressList.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 获取数据库列表
const fetchDatabaseList = async () => {
  if (!selectedAddress.value) return
  
  try {
    const { id, host, port, userName, passWord } = selectedAddress.value
    const response = await api.binlog.getDataBaseList({ id, host, port, userName, passWord })
    
    if (response.code === 200) {
      dbOptions.value = response.data || []
      // 如果地址有预设的dbName，则自动选中
      if (selectedAddress.value.dbName) {
        searchForm.dbName = selectedAddress.value.dbName
      }
    } else {
      ElMessage.error(response.msg || '获取数据库列表失败')
      dbOptions.value = []
    }
  } catch (error) {
    console.error('获取数据库列表失败:', error)
    ElMessage.error('获取数据库列表失败')
    dbOptions.value = []
  }
}

// 获取表列表
const fetchTableList = async (dbName) => {
  if (!selectedAddress.value || !dbName) {
    tableOptions.value = []
    return
  }
  
  try {
    const { id, host, port, userName, passWord } = selectedAddress.value
    const response = await api.binlog.getDataTableList({
      id,
      host,
      port,
      userName,
      passWord,
      dbName
    })
    
    if (response.code === 200) {
      tableOptions.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取表列表失败')
      tableOptions.value = []
    }
  } catch (error) {
    console.error('获取表列表失败:', error)
    ElMessage.error('获取表列表失败')
    tableOptions.value = []
  }
}

// 处理地址选择变化
const handleAddressChange = (addressId) => {
  if (!addressId) {
    searchForm.dbName = ''
    searchForm.tableName = ''
    searchForm.host = ''
    searchForm.port = ''
    searchForm.userName = ''
    searchForm.passWord = ''
    searchForm.id = ''
    dbOptions.value = []
    tableOptions.value = []
    selectedAddress.value = null
    return
  }
  
  selectedAddress.value = addressList.value.find(addr => addr.id === addressId)
  if (selectedAddress.value) {
    // 设置连接信息到searchForm
    searchForm.host = selectedAddress.value.host
    searchForm.port = selectedAddress.value.port
    searchForm.userName = selectedAddress.value.userName
    searchForm.passWord = selectedAddress.value.passWord
    searchForm.id = selectedAddress.value.id
    
    fetchDatabaseList().then(() => {
      // 仅在地址变化时设置预设库名
      if (selectedAddress.value?.dbName && dbOptions.value.includes(selectedAddress.value.dbName)) {
        searchForm.dbName = selectedAddress.value.dbName
        // 获取表列表
        fetchTableList(selectedAddress.value.dbName).then(() => {
          // 仅在地址初次选择时设置预设表名
          if (selectedAddress.value?.tableName && tableOptions.value.includes(selectedAddress.value.tableName)) {
            searchForm.tableName = selectedAddress.value.tableName
          }
        })
      }
    })
  }
}

// 处理数据库选择变化
const handleDbChange = async (dbName) => {
  // 立即清空表名和表选项
  searchForm.tableName = ''
  tableOptions.value = []
  
  // 确保DOM更新完成
  await nextTick()
  
  // 如果选择了有效的库名且有选中的地址，则获取表列表
  if (dbName && selectedAddress.value) {
    try {
      await fetchTableList(dbName)
    } catch (error) {
      console.error('获取表列表失败:', error)
      ElMessage.error({
        message: `获取表列表失败: ${error.message || '未知错误'}`,
        duration: 3000
      })
    }
  }
}

// 获取历史SQL列表
const fetchHistorySqlList = async () => {
  tableLoading.value = true
  emptyText.value = '加载中...'
  try {
    const data = {
      id: searchForm.id,
      addressName: searchForm.addressName,
      host: searchForm.host,
      port: searchForm.port,
      userName: searchForm.userName,
      passWord: searchForm.passWord,
      dbName: searchForm.dbName,
      tableName: searchForm.tableName,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime
    }

    const response = await api.binlog.getHisSqlList(data, pagination.pageNum, pagination.pageSize)

    // 检查响应中是否包含认证错误信息
    if (response.code === 401 || response.code === 403) {
      ElMessage.error('认证失败，请重新登录')
      return
    }

    if (response.code === 200) {
      sqlList.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.pageSize = response.data.size || 10
      
      emptyText.value = searchForm.addressName || searchForm.dbName || 
                       searchForm.tableName || searchForm.startTime || 
                       searchForm.endTime ? '未找到匹配的数据' : '暂无数据'
    } else {
      ElMessage.error(response.msg || '获取历史SQL列表失败')
      sqlList.value = []
      pagination.total = 0
      emptyText.value = '获取数据失败'
    }
  } catch (error) {
    console.error('获取历史SQL列表失败:', error)
    ElMessage.error('获取历史SQL列表失败')
    sqlList.value = []
    pagination.total = 0
    emptyText.value = '获取数据失败'
  } finally {
    tableLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchHistorySqlList()
}

// 重置表单
const resetForm = () => {
  Object.assign(searchForm, {
    id: '',
    addressName: '',
    host: '',
    port: '',
    userName: '',
    passWord: '',
    dbName: '',
    tableName: '',
    startTime: '',
    endTime: ''
  })
  dbOptions.value = []
  tableOptions.value = []
  selectedAddress.value = null
  handleSearch()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchHistorySqlList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  fetchHistorySqlList()
}

// 组件挂载时只获取地址列表，不进行查询
onMounted(() => {
  fetchAddressList()
})
</script>

<style scoped>
.history-sql-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.icon-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.icon-btn:hover {
  transform: scale(1.1);
}

.icon-btn .el-icon {
  font-size: 16px;
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.responsive-pagination {
  --el-pagination-button-width: 32px;
  --el-pagination-button-height: 32px;
}

@media screen and (max-width: 768px) {
  .history-sql-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
  }

  .icon-btn {
    width: 28px;
    height: 28px;
  }
  
  .icon-btn .el-icon {
    font-size: 14px;
  }

  .responsive-pagination {
    --el-pagination-button-width: 28px;
    --el-pagination-button-height: 28px;
  }
}
</style>

<style scoped>
.history-sql-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-form {
  margin-bottom: 20px;
}
</style>
